#!/bin/bash

set -e          # exit on error
set -o pipefail # exit on pipeline error
set -u          # treat unset variable as error

. /minioslib || exit 1

SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
APP="codium"
APP_NAME="VSCodium"
APP_EXECUTABLE="codium"
APP_MODULE_NUMBER="6"

get_latest_package_url() {
    curl --silent "https://api.github.com/repos/$1/releases/latest" |      # Get latest release from GitHub api
        grep '"browser_download_url":' | grep "$DISTRIBUTION_ARCH.deb"\" | # Get tag line
        sed -E 's/.*"([^"]+)".*/\1/'                                       # Pluck JSON value
}

URL=$(get_latest_package_url VSCodium/vscodium)

wget $URL &&
    pkg update -y &&
    pkg install ./$(ls codium*$DISTRIBUTION_ARCH.deb) &&
    rm -f ./$(ls codium*$DISTRIBUTION_ARCH.deb)

if grep slax /etc/hostname >/dev/null; then
    cat <<EOF >/usr/bin/fblive-add-$APP.sh
#!/bin/bash
if [ -f /var/cache/fblive-add-$APP.addon ]; then
    if ! grep $APP_EXECUTABLE /usr/bin/fbliveapp >/dev/null; then
        cp /usr/bin/fbliveapp /usr/bin/fbliveapp.$APP.bak
        sed -i "/shift/ e cat /var/cache/fblive-add-$APP.addon" /usr/bin/fbliveapp
        sed -i 's,exec "\$EXECUTABLE" "\$@",exec "\$EXECUTABLE" \$ARGS "\$@",g' /usr/bin/fbliveapp
        #rm /var/cache/fblive-add-$APP.addon
        if [ -f /usr/share/applications/$APP.desktop ]; then
            rm /usr/share/applications/$APP.desktop
        fi
    fi
fi

EOF
    chmod +x /usr/bin/fblive-add-$APP.sh
    cat <<EOF >/usr/lib/systemd/system/fblive-add-$APP.service
[Unit]
Description=Adding $APP_NAME to fbliveapp
#After=network.target

[Service]
Type=oneshot
ExecStart=/usr/bin/fblive-add-$APP.sh
RemainAfterExit=true
ExecStop=
StandardOutput=journal

[Install]
WantedBy=multi-user.target

EOF
    cat <<EOF >/usr/share/applications/$APP_MODULE_NUMBER$APP.desktop
[Desktop Entry]
Version=1.0
Name=$APP_NAME
GenericName=$APP_NAME
Exec=fbliveapp $APP %U
Terminal=false
X-MultipleArgs=false
Type=Application
Icon=$APP.png
Categories=Network;WebBrowser;
MimeType=audio/*;image/*;video/*;application/pdf;application/x-pdf;text/html;text/xml;application/xhtml_xml;application/x-mimearchive;x-scheme-handler/http;x-scheme-handler/https;
StartupWMClass=$APP
StartupNotify=true

EOF
    cat <<EOF >/var/cache/fblive-add-$APP.addon
if [ "\$1" = "$APP" ]; then
   NAME="$APP_NAME"
   EXECUTABLE="/usr/bin/$APP_EXECUTABLE"
   ARGS="--no-sandbox --user-data-dir ~/.vscode"
   GUEST=true
fi

EOF
    systemctl enable fblive-add-$APP.service 
fi

PACKAGE=$APP_EXECUTABLE
echo "PACKAGE=$PACKAGE" >/.package
echo "VERSION=$(dpkg -s $PACKAGE | grep Version | sed 's/Version: //g' | sed 's/:/-/g')" >>/.package